﻿using System;
using System.Collections.Generic;
using System.Linq;
using Xenta.Entities;
using Xenta.Enums;
using Xenta.Security;
using Xenta.Utils;

namespace Xenta.Operations
{
    public class ImportLookupAttributes : ImportOperation,
        ISecuredOperation
    {
        #region Properties

        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("SYS");
            }
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow, out int result)
        {
            result = 0;
            var languages = uow.Execute(new SearchLanguages()).Result;

            foreach(var i in Objects)
            {
                if(!i.ContainsKey("EntityID") ||
                    !i.ContainsKey("DisplayOrder") ||
                    !i.ContainsKey("Flags"))
                {
                    continue;
                }

                int entityID = i["EntityID"].ParseAs(0);
                int displayOrder = i["DisplayOrder"].ParseAs(0);
                var flags = i["Flags"].ParseAs<LookupAttributeFlags>();
                LookupAttributeEntity entity = null;

                if(entityID != 0)
                {
                    entity = uow.Execute(new UpdateLookupAttribute
                    {
                        EntityID = entityID,
                        DisplayOrder = displayOrder,
                        Flags = flags
                    }).Result;
                }
                else
                {
                    entity = uow.Execute(new CreateLookupAttribute
                    {
                        DisplayOrder = displayOrder,
                        Flags = flags
                    }).Result;
                }

                foreach(var l in languages.Where(x => i.ContainsKey(x.Code)))
                {
                    string tmp = i[l.Code];
                    if(String.IsNullOrWhiteSpace(tmp))
                        continue;

                    var nv = tmp.Split(new[]
                    {
                        ':'
                    }, 2);
                    if(nv.Length != 2)
                        continue;

                    uow.Execute(new SaveLookupAttributeTranslation
                    {
                        HolderID = entity.EntityID,
                        LanguageID = l.EntityID,
                        Name = nv[0],
                        Value = nv[1]
                    });
                }
                result++;
            }
        }

        #endregion
    }
}
